<template>
	<view class="_CreateDtlFormContainerMobile">
		<!-- <view class="formLabel text-xl padding-xs bg-gradual-blue margin-bottom-xs">{{ datasource.Name }}</view> -->

		<template v-for="(item1, index1) in formItem">
			<view :key="item1" class="itemRow">
				<template v-for="(item2, index2) in item1.temp">
					<create-form-item
						:key="item2"
						:ref="'' + index1 + index2 + item2.originName"
						:form-item-type="item2.formItemType"
						:value="item2.value"
						:prop-name="item2.originName"
						:options="item2.options"
						:form-disable="formdisabled"
						:multi-option="item2.multiOptions ? item2.multiOptions : []"
						@value-change="handleValueChange($event, index1, index2)"
						@validate-item="handleValidateItem($event, index1, index2)"
					/>
				</template>
				<view class="itemOpeCon">
					<button class="cu-btn round line-grey sm margin-xs"><text class="cuIcon-move" @click="minusClick(item1, index1)"></text></button>
				</view>
			</view>
		</template>

		<view class="topOpeCon">
			<view class="btnCon">
				<button v-if="!formdisabled && datasource.IsReadonly == '0'" class="cu-btn block line-orange  margin-xs" @click="addFormItem(undefined)">
					<text class="cuIcon-add"></text>
				</button>
			</view>
			<view class="btnCon">
				<button v-if="!formdisabled && (datasource.IsReadonly == '0' || datasource.IsDelete)" class="cu-btn block bg-blue  margin-xs" @click="saveClick">保存</button>
			</view>
		</view>
	</view>
</template>

<script>
import { mapActions } from 'vuex';
import CreateFormItem from '../create-form-item/create-form-item2.vue';
export default {
	components: {
		CreateFormItem
	},
	props: {
		datasource: {
			type: Object,
			default: () => {
				return {};
			}
		},
		flow: {
			type: Object,
			default: () => {
				return {};
			}
		},
		formdisabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			formItem: [], //二维数组
			form: {},
			colTemplate: []
		};
	},
	watch: {
		datasource: {
			deep: true,
			immediate: true,
			handler(val) {
				if (val && val.No) {
					console.log('dtl', val);
					this.initData(val);
				}
			}
		}
	},
	methods: {
		...mapActions({
			dtlInit: 'flow/dtlInit',
			deleteDtlRow: 'flow/deleteDtlRow',
			saveDtlRow: 'flow/saveDtlRow'
		}),
		initData(source) {
			this.dtlInit({
				WorkID: this.flow.WorkID,
				NodeID: this.flow.FK_Node,
				FK_Node: this.flow.FK_Node,
				FK_Flow: this.flow.FK_Flow,
				FK_MapData: source.FK_MapData,
				EnsName: source.No,
				RefPKVal: this.flow.WorkID,
				IsReadonly: source.IsReadonly,
				Version: source.DtlVer + 1
			})
				.then(res => {
					console.log('dtlRes', res);
					this.createTemplate(res);
				})
				.catch(err => {
					console.log(err);
				});
		},
		createTemplate(dtlRes) {
			let temp = [];
			let arr = [];
			let selectObj = {}; // 枚举数组按EnumKey组成的对象
			let defaultValueObj = {};
			let athObj = {}; // 附件
			let extObj = {}; // 特殊处理对象
			let uiArray = [];
			if (dtlRes.Sys_Enum && dtlRes.Sys_Enum.length > 0) {
				dtlRes.Sys_Enum.forEach((e, i) => {
					if (selectObj[e.EnumKey]) {
						selectObj[e.EnumKey].push({
							...e,
							label: e.Lab,
							value: e.IntKey,
							Name: e.Lab,
							No: '' + e.IntKey
						});
					} else {
						selectObj[e.EnumKey] = [
							{
								...e,
								label: e.Lab,
								value: '' + e.IntKey,
								Name: e.Lab,
								No: '' + e.IntKey
							}
						];
					}
				});
			}
			if (dtlRes.MainTable && dtlRes.MainTable.length > 0) {
				defaultValueObj = dtlRes.MainTable[0];
			}
			if (dtlRes.Sys_FrmAttachment && dtlRes.Sys_FrmAttachment.length > 0) {
				dtlRes.Sys_FrmAttachment.forEach((e, i) => {
					if (athObj[e.MyPK]) {
						athObj[e.MyPK].push(e);
					} else {
						athObj[e.MyPK] = [e];
					}
				});
			}
			if (dtlRes.Sys_MapExt && dtlRes.Sys_MapExt.length > 0) {
				dtlRes.Sys_MapExt.forEach(e => {
					extObj[e.AttrOfOper] = e;
				});
			}
			//创建模板
			for (let i = 0; i < dtlRes.Sys_MapAttr.length; i++) {
				let mapAttr = dtlRes.Sys_MapAttr[i];
				if (mapAttr.UIVisible == 0) {
					continue;
				}
				// 外部数据类型
				if (mapAttr.LGType == '0' && mapAttr.MyDataType == '1' && mapAttr.UIContralType == 1) {
					let selectOption = dtlRes[mapAttr.KeyOfEn] || dtlRes[mapAttr.UIBindKey];
					if (selectOption == undefined) {
						if (selectObj[mapAttr.UIBindKey]) {
							selectOption = selectObj[mapAttr.UIBindKey];
						} else {
							selectOption = [];
						}
					}
					let uiName = '';
					let formItemType = 6;
					if (mapAttr.UIContralType == 1) {
						uiName = 'DDL_' + mapAttr.KeyOfEn;
					} else if (mapAttr.UIContralType == 3) {
						uiName = 'RB_' + mapAttr.KeyOfEn;
						formItemType = 8;
					}
					temp.push({
						formItemType: formItemType,
						value: '',
						propName: uiName,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							selectOption
						}
					});
					continue;
				}
				// 外键类型
				if (mapAttr.LGType == '2' && mapAttr.MyDataType == '1') {
					let selectOption = dtlRes[mapAttr.KeyOfEn] || dtlRes[mapAttr.UIBindKey] || [];
					temp.push({
						formItemType: 6,
						value: '',
						propName: 'TB_' + mapAttr.KeyOfEn,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							selectOption
						}
					});
					continue;
				}
				// 文本框、附件
				if (mapAttr.MyDataType == '1') {
					// 附件
					if (mapAttr.UIContralType == '6') {
						continue;
					}
					// 签字板
					if (mapAttr.UIContralType == '8') {
						continue;
					}
					// 评分控件
					if (mapAttr.UIContralType == '101') {
						continue;
					}
					//  地图（划掉） 地区选择器
					if (mapAttr.UIContralType == '4') {
						let uiName = 'smc_' + mapAttr.KeyOfEn;
						let formItemType = 9;
						temp.push({
							formItemType: formItemType,
							value: '',
							propName: uiName,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOptions(mapAttr)
							}
						});
						continue;
					}
					//图片
					if (mapAttr.UIContralType == '11') {
						let defaultValue = defaultValueObj[mapAttr.KeyOfEn] || (dtlRes.Sys_FrmImg.length > 0 ? dtlRes.Sys_FrmImg[0].ImgURL : '');
						let imgUrls = [];
						if (defaultValue) {
							imgUrls = defaultValue.split(',');
						}
						temp.push({
							formItemType: 11,
							value: defaultValue,
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOptions(mapAttr),
								imgUrls
							}
						});
						continue;
					}
					// 进度条
					if (mapAttr.UIContralType == '50') {
						continue;
					}
					// 普通文本框
					if (mapAttr.UIHeight <= 40) {
						temp.push({
							formItemType: 1,
							value: '',
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOptions(mapAttr),
								maxlength: mapAttr.MaxLen,
								minlength: mapAttr.MinLen
							}
						});
						continue;
					}

					// 文本域
					if (mapAttr.UIVisible) {
						temp.push({
							formItemType: 2,
							value: '',
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOptions(mapAttr),
								maxlength: mapAttr.MaxLen,
								minlength: mapAttr.MinLen
							}
						});
						continue;
					}
				}

				// 日期类型
				if (mapAttr.MyDataType == 6) {
					let frmDate = mapAttr.IsSupperText;
					let dateFmt = '';
					let dateParams = {
						year: false,
						month: false,
						day: false
					};
					if (frmDate == 0) {
						dateFmt = 'yyyy-MM-dd';
						dateParams = {
							year: true,
							month: true,
							day: true
						};
					} else if (frmDate == 3) {
						dateFmt = 'yyyy-MM';
						dateParams = {
							year: true,
							month: true,
							day: false
						};
					} else if (frmDate == 6) {
						dateFmt = 'MM-dd';
						dateParams = {
							year: false,
							month: true,
							day: true
						};
					}
					temp.push({
						formItemType: 3,
						value: '',
						propName: 'TB_' + mapAttr.KeyOfEn,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							dateFormat: dateFmt,
							dateParams
						}
					});
					continue;
				}

				// 时期时间类型
				if (mapAttr.MyDataType == 7) {
					let frmDate = mapAttr.IsSupperText;
					let dateFmt = '';
					let timeFmt = '';
					let datePickerType = '';
					let formItemType = 12;
					let defaultValue = defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal;
					let dateValue = '';
					let timeValue = '';
					let dateParams = {
						year: false,
						month: false,
						day: false,
						hour: false,
						minute: false,
						second: false
					};
					if (frmDate == 1) {
						dateFmt = 'yyyy-MM-dd';
						timeFmt = 'HH:mm';
						datePickerType = 'datetime';
						dateParams = {
							year: true,
							month: true,
							day: true,
							hour: true,
							minute: true,
							second: false
						};
					} else if (frmDate == 2) {
						dateFmt = 'yyyy-MM-dd';
						timeFmt = 'HH:mm:ss';
						datePickerType = 'datetime';
						dateParams = {
							year: true,
							month: true,
							day: true,
							hour: true,
							minute: true,
							second: true
						};
					} else if (frmDate == 4) {
						timeFmt = 'HH:mm';
						formItemType = 4;
						dateParams = {
							year: false,
							month: false,
							day: false,
							hour: true,
							minute: true,
							second: false
						};
					} else if (frmDate == 5) {
						timeFmt = 'HH:mm:ss';
						formItemType = 4;
						dateParams = {
							year: false,
							month: false,
							day: false,
							hour: true,
							minute: true,
							second: true
						};
					}
					temp.push({
						formItemType,
						value: '',
						propName: 'TB_' + mapAttr.KeyOfEn,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							dateFormat: dateFmt,
							timeFormat: dateFmt,
							datePickerType,
							dateParams
						}
					});
					continue;
				}

				// boolen 类型.
				if (mapAttr.MyDataType == 4) {
					temp.push({
						formItemType: 7,
						value: '',
						propName: 'CB_' + mapAttr.KeyOfEn,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr)
						}
					});
					continue;
				}

				// 枚举类型
				if (mapAttr.MyDataType == 2 && mapAttr.LGType == 1) {
					let selectOption = dtlRes[mapAttr.KeyOfEn] || dtlRes[mapAttr.UIBindKey];
					if (selectOption == undefined) {
						if (selectObj[mapAttr.UIBindKey]) {
							selectOption = selectObj[mapAttr.UIBindKey];
						} else {
							selectOption = [];
						}
					}
					let uiName = '';
					let formItemType = 6;
					if (mapAttr.UIContralType == 1) {
						uiName = 'DDL_' + mapAttr.KeyOfEn;
					} else if (mapAttr.UIContralType == 3) {
						uiName = 'RB_' + mapAttr.KeyOfEn;
						formItemType = 8;
					}
					temp.push({
						formItemType: formItemType,
						value: '',
						propName: uiName,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							selectOption
						}
					});
					continue;
				}

				// 数字类型
				if (mapAttr.MyDataType == 5 || mapAttr.MyDataType == 3 || mapAttr.MyDataType == 2 || mapAttr.MyDataType == 8) {
					let precision = 0;
					let attrdefVal = mapAttr.DefVal;
					if (attrdefVal != null && attrdefVal !== '' && attrdefVal.indexOf('.') >= 0) {
						precision = attrdefVal.substring(attrdefVal.indexOf('.') + 1).length;
					}

					temp.push({
						formItemType: 5,
						value: '',
						propName: 'TB_' + mapAttr.KeyOfEn,
						originName: mapAttr.KeyOfEn,
						idx: i,
						options: {
							...this.createOptions(mapAttr),
							precision,
							numberMax: Math.pow(10, mapAttr.MaxLen + 1) - 1,
							numberMin: Math.pow(10, mapAttr.MinLen)
						}
					});
					continue;
				}
			}

			console.log('temp', temp);
			this.colTemplate = temp;

			dtlRes.DBDtl.forEach((e, i) => {
				this.addFormItem(e);
			});
		},
		createOptions(mapAttr) {
			return {
				tip: mapAttr.Tip,
				colSpan: mapAttr.ColSpan == 1 ? 7 : 22,
				isEnable: mapAttr.UIIsEnable,
				label: mapAttr.Name,
				isRequired: !!mapAttr.UIIsInput
			};
		},
		addFormItem(defObj) {
			if (this.colTemplate.length == 0) {
				return;
			}
			let temp = JSON.parse(JSON.stringify(this.colTemplate));
			if (defObj) {
				//初始化
				temp.forEach((e, i) => {
					if (defObj[e.originName]) {
						e.value = defObj[e.originName];
					}
				});
				this.formItem.push({ ...defObj, temp });
			} else {
				//动态添加表单项
				this.formItem.push({ temp, OID: 0, FID: 0, RefPK: 0 });
			}
		},
		handleValueChange(obj, index1, index2) {
			console.log(obj, index1, index2);
			this.formItem[index1][obj.key] = obj.value;
			this.formItem[index1].temp[index2].value = obj.value;
		},
		handleValidateItem(obj, index1, index2) {
			if (obj.isRequired) {
				if (obj.value) {
					obj.callback();
				} else {
					obj.callback('请输入');
				}
			} else {
				obj.callback();
			}
		},
		delItem(item, index) {
			if (item.OID) {
				this.deleteDtlRow({
					...item,
					FK_MapDtl: this.datasource.No
				})
					.then(res => {
						console.log(res);
						if (res == '删除成功') {
							this.formItem.splice(index, 1);
						}
					})
					.catch(err => {
						console.log(err);
					});
			} else {
				this.formItem.splice(index, 1);
			}
		},
		async saveClick() {
			let arr = [];
			for (let i = 0; i < this.formItem.length; i++) {
				let e = this.formItem[i];
				let cache = JSON.parse(JSON.stringify(e));
				delete cache.temp;
				let result = await this.saveDtlRow({
					...cache,
					FK_MapData: this.datasource.FK_MapData,
					FK_MapDtl: this.datasource.No,
					FK_Node: this.flow.FK_Node,
					RefPKVal: this.flow.WorkID
				});
			}
			this.formItem = [];
			this.colTemplate = [];
			this.initData(this.datasource);
		},
		minusClick(item, index) {
			let self = this;
			uni.showModal({
				title: '删除',
				content: '确定删除该项？',
				success(res) {
					if (res.confirm) {
						self.delItem(item, index);
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
._CreateDtlFormContainerMobile {
	.formLabel {
		text-align: center;
	}
	.dtlFormCon {
		padding: 16rpx;
	}
	.topOpeCon {
		display: flex;
		flex-wrap: wrap;
		.btnCon {
			flex: 1;
			padding: 16rpx;
			.el-button {
				width: 100%;
			}
		}
	}
	.el-button.is-round {
		padding: 16rpx;
	}
	.itemRow {
		border-bottom: 1px solid #eee;
		padding-bottom: 4rpx;
	}
	.dtlFormCon {
		padding: 8rpx;
	}
	.itemOpeCon {
		text-align: center;
	}
}
</style>
